package com.renwei.yunlong.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseFragment;
import com.renwei.yunlong.bean.KnowDetailsBean;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import java.util.HashMap;

import github.benjamin.tbsreader.bridge.DefaultHandler;
import github.benjamin.tbsreader.bridge.SimpleBridgeWebViewClientListener;
import github.benjamin.tbsreader.bridge.TbsBridgeWebView;

/**
 * Created by wangqi on 2018/4/13.
 */

@SuppressLint("ValidFragment")
public class KnowDetailsFragment extends BaseFragment implements View.OnClickListener {
    TbsBridgeWebView webView;
    private String TAG = KnowDetailsFragment.class.getName();
    private String knowledgeId;

    @SuppressLint("ValidFragment")
    public KnowDetailsFragment(String knowledgeId) {
        this.knowledgeId = knowledgeId;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_know_details;
    }


    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        webView = view.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSaveFormData(false);
        webView.getSettings().setSavePassword(false);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        //设定支持h5viewport
        webView.getSettings().setUseWideViewPort(true);
        // 自适应屏幕.
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.setBridgeWebViewClientListener(new SimpleBridgeWebViewClientListener());
        //=======================此方法必须调用==========================
        webView.setDefaultHandler(new DefaultHandler());
        //=======================js桥使用改方法替换原有setWebViewClient()方法==========================
        webView.setBridgeWebViewClientListener(new SimpleBridgeWebViewClientListener() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i(TAG, "超链接：" + url);
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap bitmap) {

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                initData();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            }

            @Override
            public boolean onReceivedSslError(WebView webView, final SslErrorHandler sslErrorHandler, SslError sslError) {
                /*String message;
                switch (sslError.getPrimaryError()) {
                    case android.net.http.SslError.SSL_UNTRUSTED:
                        message = "证书颁发机构不受信任";
                        break;
                    case android.net.http.SslError.SSL_EXPIRED:
                        message = "证书过期";
                        break;
                    case android.net.http.SslError.SSL_IDMISMATCH:
                        message = "网站名称与证书不一致";
                        break;
                    case android.net.http.SslError.SSL_NOTYETVALID:
                        message = "证书无效";
                        break;
                    case android.net.http.SslError.SSL_DATE_INVALID:
                        message = "证书日期无效";
                        break;
                    case android.net.http.SslError.SSL_INVALID:
                    default:
                        message = "证书错误";
                        break;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("提示").setMessage(message + "，是否继续").setCancelable(true)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                sslErrorHandler.proceed();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                sslErrorHandler.cancel();
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();*/
                sslErrorHandler.proceed();
                return true;
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });
        String url = Api.$().KNOWLEDGE_URL;
        webView.loadUrl(url);
        webView.setCustom("TestJavascriptBridge");
    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("knowledgeId", knowledgeId);
        if ("1".equals(companyType)) {
            map.put("createUserId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {
            map.put("createUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        ServiceRequestManager.getManager().getKnowDetails(getActivity(), JsonMapUtil.mapToJson(map), new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
                KnowDetailsBean knowDetailsBean = new Gson().fromJson(result, KnowDetailsBean.class);
                if (knowDetailsBean.getMessage().getCode() == 200) {
                    KnowDetailsBean.RowsBean bean = knowDetailsBean.getRows();
                    if (bean.getContent() != null) {
                        String content = new Gson().toJson(bean);
                           /*showCenterSuccessMsg(content);*/
                        webView.evaluateJavascript("getKnowledge(" + content + ")", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String s) {

                            }
                        });
                    }
                }
            }

            @Override
            public void onException(int requestId, String code) {
                showTopWrongMsg("网络加载失败");
            }
        });
    }

    @Override
    public void onClick(View v) {
        getActivity().finish();
    }


}
